package com.securecrt;

import java.io.IOException;
import java.util.ArrayList;

import org.sshbot.MainActivity;
import org.sshbot.R;
import org.sshbot.Ssh;
import org.sshbot.TerminalView;
import org.sshbot.transport.SSH;
import org.sshbot.transport.Transport;
import org.sshbot.util.Utils;

import com.jcraft.jsch.JSchException;
import com.securecrt.pojo.SaveSessionAdapter;
import com.securecrt.pojo.Savesession;
import com.securecrt.pojo.SQLHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.Toast;

public class SaveSession extends Activity {

	ArrayList<Savesession> list=new ArrayList<Savesession>();
	SQLHelper eventsData;

	ListView listSaveSession;
	String host,port, user,pass, mac, cipher;
	Button btBack, btHome,btNewConnect;

    ProgressDialog pro;
    private Transport transport;
    
    public static boolean isPortrait = true;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.savesession);
		
		eventsData=new SQLHelper(this);
    	cipher = getIntent().getExtras().getString("cipher");
    	mac = getIntent().getExtras().getString("mac");
        Cursor cursor=getEvents();
        showEvents(cursor);
        
        listSaveSession=(ListView)findViewById(R.id.listSaveSession);
        SaveSessionAdapter adapter1 = new SaveSessionAdapter(this, list);
        listSaveSession.setAdapter(adapter1);
        
        int[] colors = {0, 0xFFFF0000, 0};
        listSaveSession.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
        listSaveSession.setDividerHeight(1);
        
        listSaveSession.setOnItemClickListener(LoginServerAuto);
        
        btBack = (Button) findViewById(R.id.btBack);
		btHome = (Button) findViewById(R.id.btHome);

		btBack=(Button)findViewById(R.id.btBack);
		btHome=(Button)findViewById(R.id.btHome);
		btBack.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				buttonBack();
			}});
		btHome.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				buttonHome();
			}});
		btNewConnect=(Button)findViewById(R.id.btNewConnect);
		btNewConnect.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				clickNewConnect();
			}
		});
	}
	
	private void clickNewConnect(){
		Intent i=new Intent(this, Ssh.class);
		startActivity(i);
	}
	private void buttonBack(){
		moveTaskToBack(true);	
		finish();
		System.exit(0);
	}
	private void buttonHome(){
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		finish();
		System.exit(0);
	}

	private void init(){
		list.clear();
		Cursor cursor=getEvents();
        showEvents(cursor);
        SaveSessionAdapter adapter1 = new SaveSessionAdapter(this, list);
        listSaveSession.setAdapter(adapter1);
	}
	private void loadingShow(final Savesession item){
    	ssh2LoginAuto(item);
//    	pro=ProgressDialog.show(this, "", getString(R.string.waiting)+"...");
//    	Thread t = new Thread(new Runnable(){
//            public void run() {
//                try{
//                	ssh2LoginAuto(item);
//                }catch (Exception e) {
//					e.printStackTrace();
//				}
//                pro.dismiss();
//            }
//        });
//        t.start();
    }
	private void ssh2LoginAuto(Savesession item){
		System.out.println();
		boolean res = connectToServer(item.getUsername()+"@"+item.getPassword()+"@"+item.getHostname()+"@"+item.getPort());
		if(!res){
			Utils.showErrorMessage(SaveSession.this,"SSH Connect Fault.");
			//Toast.makeText(Ssh.this,"SSH Connect Fault.", Toast.LENGTH_SHORT).show();			
			return;
		}
	}
	private SSH sh;
	private boolean connectToServer(final String uri) {
		if (!uri.contains("@")) {
			return false;
		}

		String[] tmp = uri.split("@");
		String username = tmp[0];
		String pass = tmp[1];
		String host = tmp[2];		
		int port = Integer.parseInt(tmp[3]);
		

		transport = null;
		sh = null;
		try {
			sh = new SSH(username,pass, host, port);			
		} catch (JSchException e) {
			e.printStackTrace();			
		}

		if(sh.isConnected()){
			transport = sh;
		}else{
			return false;
		}

		if (transport != null) {
			TerminalView tv = new TerminalView(this, transport);
			
			setContentView(tv);
		}

		return true;
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// TODO save this to somewhere better place
		isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();

	//	transport.disconnect();
	}

	private void showEx(final Savesession item){
		AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
		alertDialog.setTitle(getString(R.string.cfConnect)+"...");
		alertDialog.setMessage(getString(R.string.cfContent));
		alertDialog.setPositiveButton(getString(R.string.btAccept), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            	loadingShow(item);
            }
        });
        alertDialog.setNeutralButton(getString(R.string.btDelete), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,    int which) {
            	SQLiteDatabase db=eventsData.getWritableDatabase();
		    	db.delete(SQLHelper.TABLE, BaseColumns._ID + "=" +item.getId(), null);
            	init();
            }
        });
        alertDialog.setNegativeButton(getString(R.string.btCancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
	            dialog.cancel();
            }
        });
        alertDialog.show();
	}
	private OnItemClickListener LoginServerAuto=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> a, View v, int position, long id) {
			// TODO Auto-generated method stub
			Savesession item=(Savesession)list.get(position);
			showEx(item);
		}
	};


	private Cursor getEvents(){
		SQLiteDatabase db=eventsData.getReadableDatabase();
		Cursor cursor=db.query(SQLHelper.TABLE, null, null, null, null,null, null);
		startManagingCursor(cursor);
		return cursor;
	}
	private void showEvents(Cursor cursor){
		StringBuilder ret=new StringBuilder("Saved Events:\n\n");
		while(cursor.moveToNext()){
			long id =cursor.getLong(0);
			String hostname=cursor.getString(1);
			String port=cursor.getString(2);
			String username=cursor.getString(3);
			String password=cursor.getString(4);
			String time_=cursor.getString(5);
			Savesession ss=new Savesession();
			ss.setId(id);
			ss.setHostname(hostname);
			ss.setPort(port);
			ss.setUsername(username);
			ss.setPassword(password);
			ss.setTime_(time_);
			list.add(ss);
		}
	}
	
	
}
